package pers.liuchengyin.qq.controller;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author liuchengyin
 * @description 登录Controller
 * @date 2021-12-17 20:25
 */
@Controller
public class LoginController {

    /**
     * 跳转至登录成功页
     */
    @RequestMapping("/index")
    public String admin(Model model){
        model.addAttribute("name", "柳成荫");
        model.addAttribute("headImgUrl", "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F202003%2F13%2F20200313175003_uwnff.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1642343525&t=149d9cba97279089bd7f0eceebc0d5cb");
        model.addAttribute("openId","123456");
        return "index";
    }

    /**
     * QQ登录请求
     */
    @RequestMapping("/loginByQQ")
    public void loginByQq(HttpServletRequest request, HttpServletResponse response) {
        // html类型，以网页形式打开
        response.setContentType("text/html;charset=utf-8");
        try {
            response.sendRedirect(new Oauth().getAuthorizeURL(request));
            System.out.println("In the QQ login...");
        } catch (QQConnectException | IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * QQ登录回调方法
     * @return
     */
    @RequestMapping("/login/qqLogin")
    public String connection(HttpServletRequest request, HttpServletResponse response, Model model) {
        try {
            // 获取AccessToken， getAccessTokenByRequest
            AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
            String accessToken = null, openID = null;
            long tokenExpireIn = 0L;
            if (StringUtils.isEmpty(accessTokenObj.getAccessToken())) {
                System.out.println("Login Failed, accessToken is blank");
                // 未获取到accessToken，可以考虑：跳转回登录界面附带一个参数进行错误提示
                return "error";
            } else {
                accessToken = accessTokenObj.getAccessToken();
                // token过期时间 - 10分钟
                tokenExpireIn = accessTokenObj.getExpireIn();
                System.out.println("accessToken" + accessToken);
                request.getSession().setAttribute("demo_access_token", accessToken);
                request.getSession().setAttribute("demo_token_expirein", String.valueOf(tokenExpireIn));

                // 根据AccessToken获取OpenId
                OpenID openIDObj = new OpenID(accessToken);
                openID = openIDObj.getUserOpenID();
                // 获取用户信息，2021.12.27-2022.1.1全部返回2(默认值)，2022年1月1日开始不再返回gender字段
                UserInfo userInfo = new UserInfo(accessToken, openID);
                UserInfoBean userInfoBean = userInfo.getUserInfo();
                // 返回码为0是正常返回，其他表示错误。
                if (userInfoBean.getRet() == 0) {
                    // 获取昵称，需要去除表情、特殊符号
                    String name = removeNonBmpUnicode(userInfoBean.getNickname());
                    // 头像Url
                    String imgUrl = userInfoBean.getAvatar().getAvatarURL100();
                    model.addAttribute("headImgUrl",imgUrl);
                    model.addAttribute("name",name);
                    model.addAttribute("openId",openID);
                } else {
                    System.out.println("QQ Login Failed, Reason is: " + userInfoBean.getMsg());
                    return "error";
                }
            }
        } catch (QQConnectException e) {
            e.printStackTrace();
            return "error";
        }
        return "index";
    }

    @GetMapping("/")
    public String goLogin(){
        return "login";
    }

    @GetMapping("/error")
    public String loginFailed(){
        return "error";
    }


    /**
     * 处理掉QQ网名中的特殊表情
     */
    public String removeNonBmpUnicode(String str) {
        if (str == null) {
            return "QQ登录用户";
        }
        str = str.replaceAll("[^\\u0000-\\uFFFF]", "");
        if ("".equals(str)) {
            str = "QQ登录用户";
        }
        return str;
    }
}
